import React from 'react'
import {Space, Input, Form, Select, Button, message} from 'antd'
import {CloseCircleOutlined} from '@ant-design/icons';
import GoBack from '@/components/TheGoBack'
import {apiGetMhcResourceDetail, apiGetMhcResourceEdit} from "@/request/callSetting/resourceSate";
import TextArea from "antd/es/input/TextArea";

const {Option} = Select

//编辑资源位设置
export default class Tips extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mhcResourceId: props.match.params.id,
            mode: props.match.params.mode,
            resourceName: '',
            activeList: [],//跳转页面list
            saveLoading: false,
            requiredUrl: true
        }
    }

    componentDidMount() {
        this.getData()
        this.getActiveList()
        message.config({maxCount: 1});
    }

    //获取数据
    getData = async () => {
        apiGetMhcResourceDetail(this.state.mhcResourceId).then(res => {
            if (res.code === 0) {
                if (res.data.detailList && res.data.detailList.length > 0) {
                    let data = res.data.detailList[0];
                    let url = [];
                    if (data.resourceConfigUrl){
                        url = data.resourceConfigUrl.split('?');
                    }
                    let parameter = null
                    if (url.length > 1) {
                        parameter = url[1].split('&').map(item => {
                            let d = item.split('=')
                            return {
                                key: d[0],
                                value: d[1]
                            }
                        })
                    }
                    this.formRef.setFieldsValue({
                        resourceConfigUrl: url[0],
                        resourceConfigText: data.resourceConfigText,
                        parameter
                    })
                }
                // 跳转页面是否必填
                let requiredUrl = true;
                if (['预约选择地址提醒','预约选择宠物提醒','预约价格提示说明'].includes(res.data.resourceName)){
                    requiredUrl = false
                }
                this.setState({
                    resourceName: res.data.resourceName,
                    requiredUrl
                })
            }
        })
    }

    // 跳转页面下拉内容
    async getActiveList() {
        await React.$post('/admin/activityLink/activityLinkList').then(res => {
            if (res.code === 0) {
                this.setState({activeList: res.data})
            }
        })
    }

    // 保存
    onFinish = (value) => {
        this.setState({
            saveLoading: true
        })
        if (value.parameter && value.parameter.length > 0) {
            let arr = []
            value.parameter.map(item => {
                arr.push(`${item.key}=${item.value}`)
            })
            value.resourceConfigUrl += '?' + arr.join('&')
        }
        delete value.parameter;
        let {mhcResourceId} = this.state
        apiGetMhcResourceEdit({
            mhcResourceId,
            detailList: [value]
        }).then(res => {
            if (res.code === 0) {
                message.success('保存成功')
                this.props.history.goBack()
            }
            this.setState({
                saveLoading: false
            })
        })
    }
    //取消并关闭弹窗
    cancel = () => {
        this.props.history.goBack()
    }

    render() {
        const {activeList, resourceName, saveLoading, mode, requiredUrl} = this.state
        return (
            <div className='p-layout-box'>
                <GoBack history={this.props.history} title={"资源位详情"}/>
                <br/>
                <Form
                    ref={(ref) => {
                        this.formRef = ref;
                    }}
                    labelCol={{span: 3}}
                    wrapperCol={{span: 5}}
                    onFinish={this.onFinish}
                    disabled={mode === 'view'}
                >
                    <Form.Item label="资源位名称">
                        <span>{resourceName}</span>
                    </Form.Item>
                    <Form.Item label="文本内容" name={'resourceConfigText'} rules={[{required: true}]}>
                        <TextArea allowClear rows={4} maxLength={150} showCount/>
                    </Form.Item>
                    <Form.Item name='resourceConfigUrl' label={'跳转页面'}
                               rules={[{required: requiredUrl, message: '请选择跳转页面'}]}>
                        <Select allowClear placeholder={'未选择'}>
                            {
                                activeList.map(item => <Option value={item.activityLink}
                                                               key={item.id}>{item.activityName}</Option>)
                            }
                        </Select>
                    </Form.Item>
                    <Form.List name="parameter">
                        {(fields, {add, remove}) => (
                            <>
                                <Form.Item label="参数">
                                    <Button type="dashed" onClick={() => add()} block>添加参数</Button>
                                </Form.Item>
                                {fields.map(({key, name, ...restField}) => (
                                    <Form.Item
                                        wrapperCol={{offset: 3, span: 5}}
                                        required={false}
                                        key={key}
                                        style={{
                                            margin: 0
                                        }}
                                    >
                                        <Space style={{display: 'flex', marginBottom: 0,}} align="baseline">
                                            <Form.Item
                                                {...restField}
                                                name={[name, 'key']}
                                                rules={[{required: true, message: '请输入参数名',}]}

                                            >
                                                <Input placeholder="参数名"/>
                                            </Form.Item>
                                            <Form.Item
                                                {...restField}
                                                name={[name, 'value']}
                                                rules={[{required: true, message: '请输入参数值'}]}
                                            >
                                                <Input placeholder="参数值"/>
                                            </Form.Item>
                                            <CloseCircleOutlined onClick={() => remove(name)}/>
                                        </Space>
                                    </Form.Item>
                                ))}

                            </>
                        )}
                    </Form.List>
                    <Form.Item wrapperCol={{offset: 3, span: 5}}>
                        <Space>
                            <Button key="back" onClick={this.cancel}>取 消</Button>
                            <Button loading={saveLoading} type="primary" htmlType="primary">确 定</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </div>
        )
    }
}
